package xl

import (
	"context"
	"encoding/json"
	"ez/apps/xl/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type Choice struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64 `json:"id" bson:"id,omitempty"`

	Question *Question `json:"question" bson:"question"` //所属题目

	QuestionId int64 `json:"questionId" bson:"questionId"` //所属题目

	Sort int64 `json:"sort" bson:"sort"` //排序

	Title string `json:"title" bson:"title"` //选项内容

	Score float64 `json:"score" bson:"score"` //分数

	Analyze string `json:"analyze" bson:"analyze"` //选项分析

	CreateAt time.Time  `json:"createAt" bson:"createAt"`
	UpdateAt time.Time  `json:"updateAt" bson:"updateAt"`
	DeleteAt *time.Time `json:"deleteAt" bson:"deleteAt"`
}

func (this *Choice) DocName() string { return "Choice" }

func (this *Choice) GetId() int64 { return this.Id }

func (this *Choice) SetId(id int64) { this.Id = id }

func (this *Choice) Create() error {
	return this.GetFactory().Create(this)
}

func (this *Choice) Replace() error {
	return this.GetFactory().Replace(this)
}

func (this *Choice) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *Choice) Delete() error {
	return this.GetFactory().Delete(this)
}

func (this *Choice) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *Choice) Destroy() error {
	return this.GetFactory().Destroy(this)
}

func (this *Choice) ToString() string {
	return string(this.ToBytes())
}

func (this *Choice) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Choice) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Choice) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}

func (this *Choice) LoadQuestion() {
	if this.QuestionId == 0 {
		return
	}
	this.Question, _ = NewQuestionCrud().FindId(this.QuestionId)
}

func (this *Choice) ClearRelationsBeforeSave() mgo.Doc {

	this.Question = nil

	return this
}

func neverUsed_Choice() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type ChoiceAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *Choice
	Session *ez.Session
}

func NewChoiceAccessControl(model *Choice, action string, session *ez.Session) *ChoiceAccessControl {
	ctrl := &ChoiceAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.ChoiceAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
